package org.example.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class ZkRegistryCenter implements RegistryCenter {

    private CuratorFramework curatorFramework;

    {
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("10.88.15.159:12181")
                //会话超时时间
                .sessionTimeoutMs(5000)
                // 重试策略  allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper);
                // retryCount 已重试次数， elapsedTimeMs 从第一次重试开始花费时间 sleeper
                // baseSleepTimeMs  maxSleepMs 最大重试次数
                .retryPolicy(new ExponentialBackoffRetry(1000, 10))
                .build();
        curatorFramework.start();
    }

    @Override
    public void register(String serviceName, String serviceAddress) throws Exception {
        // zk节点
        String servicePath = "dubbo-api/" + serviceName;
        if (curatorFramework.checkExists().forPath(servicePath) == null) {
            curatorFramework.create()
                    // 并递归创建父节点
                    .creatingParentsIfNeeded()
                    // PERSISTENT 持久化节点   EPHEMERAL  临时节点（会话内）
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(servicePath, "a".getBytes());
        }
        String addressPath = servicePath.concat("/") + serviceAddress;

        if (curatorFramework.checkExists().forPath(addressPath) == null) {
            String hostNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL)
                    .forPath(addressPath, "a".getBytes());

            System.out.println("register Success" + hostNode);
        }
    }
}
